﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using Chatter.CoreClient;

namespace ChatClient
{
    public partial class frmUserPreference : Form
    {
        private bool m_firstClick;
        private Point m_firstClickLoc;
        private Chatter.CoreClient.CMDClient client;
        private bool canClose;
        private bool _modified;

        public bool modified
        {
            get { return _modified; }
        }

        public frmUserPreference(CMDClient cmdClient)
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
            this.canClose = false;
            this._modified = false;
            this.client = cmdClient;
            this.client.CommandReceived += new CommandReceivedEventHandler(CommandReceived);
        }

        void CommandReceived(object sender, Chatter.CoreClient.CommandEventArgs e)
        {
            if (e.Command.CommandType == Chatter.CoreClient.CommandType.UserSetPreferences)
            {
                if (Convert.ToBoolean(e.Command.MetaData.ToLower()))
                {
                    this.client.password = this.txtNewUserPwd.Text.Trim();
                    this._modified = true;
                    this.canClose = true;
                    this.Close();
                }
            }
        }

        private void frmUserPreference_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                if (this.m_firstClick == false)
                {
                    this.m_firstClick = true;
                    this.m_firstClickLoc = new Point(e.X, e.Y);
                }

                this.Location = new Point(
                    this.Location.X + e.X - m_firstClickLoc.X,
                    this.Location.Y + e.Y - m_firstClickLoc.Y
                );
            }
            else
            {
                this.m_firstClick = false;
            }
        }

        private bool IsValidEmailEntered(string email)
        {
            var r = new System.Text.RegularExpressions.Regex(@"^([0-9a-zA-Z]([-\.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$");
            return r.IsMatch(email);
        }

        private void _SetError(string errorMessage)
        {
            this.pbInformation.Image = Properties.Resources.iconError;
            this.lblInformation.Text = errorMessage;
            this.lblInformation.ForeColor = Color.Crimson;
            this.pbInformation.Visible = true;
            this.lblInformation.Visible = true;
            this.SetEnablity(true);
        }

        private void LoginToServer()
        {
            // Rien n'est coché, on ferme la fenêtre
            if (!this.cbxPwdModify.Checked && !this.cbxEmailModify.Checked)
            {
                this.canClose = true;
                this.Close();
                return;
            }

            string newPwd = "";
            string newMail = "";

            // Changement de mot de passe demandé
            if (this.cbxPwdModify.Checked)
            {
                // Un des champs sont vides
                if (String.IsNullOrEmpty(this.txtUserPwd.Text.Trim()) || String.IsNullOrEmpty(this.txtNewUserPwd.Text.Trim()) || String.IsNullOrEmpty(this.txtRepeatUserPwd.Text.Trim()))
                {
                    this._SetError("Champs pour la modification du mot de passe obligatoires.");
                    return;
                }

                // L'ancien mot de passe est incorrect
                if (!this.client.password.Equals(this.txtUserPwd.Text))
                {
                    this._SetError("L'ancien mot de passe ne correspond pas à celui rentré.");
                    return;
                }
                // Les deux mots de passe ne correspondent pas
                if (!this.txtNewUserPwd.Text.Equals(this.txtRepeatUserPwd.Text))
                {
                    this._SetError("Les deux mots de passe ne correspondent pas.");
                    return;
                }

                newPwd = ShareUtils.CalculateMD5Hash(this.txtNewUserPwd.Text.Trim());
            }

            // Changement d'adresse email demandé
            if (this.cbxEmailModify.Checked)
            {
                // Adresse email non spécifiée
                if(String.IsNullOrEmpty(this.txtUserMail.Text.Trim()))
                {
                    this._SetError("L'adresse email est obligatoire.");
                    return;
                }

                // L'adresse email est invalide
                if (this.cbxEmailModify.Checked && !IsValidEmailEntered(this.txtUserMail.Text.Trim()))
                {
                    this._SetError("Veuillez spécifier une adresse email valide : user@domain.tld !");
                    return;
                }

                newMail = this.txtUserMail.Text.Trim();
            }

            string data = newPwd + ":" + newMail;

            Command cmd = new Command(Chatter.CoreClient.CommandType.UserSetPreferences, this.client.IP, data);
            cmd.SenderName = this.client.NetworkName;
            cmd.SenderIP = this.client.IP;
            this.client.SendCommand(cmd);
        }

        private void btnEnter_Click(object sender, EventArgs e)
        {
            this.SetEnablity(false);
            this.LoginToServer();
        }

        private void SetEnablity(bool enable)
        {
            this.btnEnter.Enabled = enable;
            this.txtUserPwd.Enabled = this.cbxPwdModify.Checked;
            this.txtNewUserPwd.Enabled = this.cbxPwdModify.Checked;
            this.txtRepeatUserPwd.Enabled = this.cbxPwdModify.Checked;
            this.txtUserMail.Enabled = this.cbxEmailModify.Checked;
            this.btnClose.Enabled = enable;
        }

        private void frmUserPreference_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!this.canClose)
                e.Cancel = true;
            else
                this.client.CommandReceived -= new Chatter.CoreClient.CommandReceivedEventHandler(CommandReceived);
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.canClose = true;
        }

        private void cbxPwdModify_CheckedChanged(object sender, EventArgs e)
        {
            bool checkedState = this.cbxPwdModify.Checked;

            this.lblUserPwd.Enabled = checkedState;
            this.lblNewUserPwd.Enabled = checkedState;
            this.lblRepeatUserPwd.Enabled = checkedState;

            this.txtUserPwd.Enabled = checkedState;
            this.txtNewUserPwd.Enabled = checkedState;
            this.txtRepeatUserPwd.Enabled = checkedState;
        }

        private void cbxEmailModify_CheckedChanged(object sender, EventArgs e)
        {
            this.lblUserMail.Enabled = this.cbxEmailModify.Checked;
            this.txtUserMail.Enabled = this.cbxEmailModify.Checked;
        }
    }
}
